<template>
	<view class="information">
		<view class="bg">
			<view class="box avatar" @click="changePhotot">
				<text class="left">头像</text>
				<image class="image" :src="baseFormData.avatarUrl" mode="aspectFit">
				</image>
			</view>
			<view class="box" @click="inputDialogToggle">
				<text class="left">用户名</text>
				<text>{{baseFormData.nickName}}</text>
			</view>
			<view class="box" @click="changeData(1)">
				<text class="left">年龄</text>
				<text>{{baseFormData.age}}</text>
			</view>
			<view class="box" @click="changeData(2)">
				<text class="left">性别</text>
				<text>{{baseFormData.gender==0?'男':baseFormData.gender==1?'女':'未设置'}}</text>
			</view>
			<view class="box" @click="changeData(3)">
				<text class="left">身高</text>
				<text>{{baseFormData.height}}</text>
			</view>
			<view class="box" @click="changeData(4)">
				<text class="left">体重</text>
				<text>{{baseFormData.weight}}</text>
			</view>
			<view class="box" @click="changeSignature">
				<text class="left">个性签名</text>
				<text class="signature">{{baseFormData.signature}}</text>
			</view>
		</view>
		<!-- 身高，体重，年龄，性别修改 -->
		<uni-popup ref="popup" background-color="#fff">
			<view class="btn">
				<text @click="()=>popup.close()" class="cancel">取消</text>
				<text @click="saveData" class="save">确定</text>
			</view>
			<picker-view :value="pickerData" @change="bindChange" class="picker-view">
				<picker-view-column v-if="type!=2">
					<view class="item" v-for="(item,index) in number" :key="index">{{item}}</view>
				</picker-view-column>
				<picker-view-column v-if="type==3||type==4">
					<view class="item" v-for="(item,index) in float" :key="index">{{item}}</view>
				</picker-view-column>
				<picker-view-column v-if="type!=1">
					<view class="item" v-for="(item,index) in unit" :key="index">{{item}}</view>
				</picker-view-column>
			</picker-view>
		</uni-popup>
		<!-- 昵称/个性签名修改 -->
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="修改昵称" placeholder="请输入昵称"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		nextTick,
		getCurrentInstance,
		onMounted
	} from 'vue'
	import {
		onLoad,onUnload
	} from '@dcloudio/uni-app'
	const {
		proxy
	} = getCurrentInstance()
	let userInfo = uni.getStorageSync('userInfo')
	// 个人基础信息
	const baseFormData = ref({
		nickName: '',
		age: '',
		height: '',
		weight: '',
		signature: '',
		avatarUrl: '',
		gender: ''
	})
	//滚动选择器数据
	const pickerData = ref([])
	//滚动选择器类型 1为年龄 2为性别 3为身高 4为体重
	const type = ref(1)
	const unit = ref([])
	const float = ref([])
	const number = ref([])
	const popup = ref()
	const inputDialog = ref()
	const tempData = ref()
	onLoad((option) => {
		if (option.baseFormData) {
			baseFormData.value = JSON.parse(option.baseFormData)
		}
		uni.$on('signature', (data) => {
			baseFormData.value.signature = data.signature
		})
	})
	onUnload(() => {
		uni.$off("signature")
	})
	// 选择图片
	const changePhotot = (e) => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				uni.showLoading({
					title: "上传头像中",
					mask: true
				})
				const item = res.tempFiles.find(item => {
					return item.size > 1024 * 1024
				})
				if (item) {
					uni.showToast({
						title: '单张图片大小不得高于1M',
						icon: "none"
					})
					return
				}
				let suffix = res.tempFiles[0].path.substring(res.tempFiles[0].path.lastIndexOf("."));
				let randomName = Date.now() + "" + String(Math.random()).substr(3, 6) + suffix
				uniCloud.uploadFile({
					filePath: res.tempFiles[0].path,
					cloudPath: res.tempFiles[0].name || randomName
				}).then(result => {
					if (result.success) {
						proxy.$http("setUserInfo", {
							avatarUrl: result.fileID
						}).then(uploadData => {
							if (!uploadData.errCode) {
								uni.showToast({
									title: uploadData.result.msg,
									icon: 'none',
									duration: 1000
								})
								userInfo.avatarUrl = result.fileID
								uni.setStorageSync('userInfo', userInfo)
								baseFormData.value.avatarUrl = result.fileID
								uni.hideLoading()
							}
						})
					} else {
						uni.showToast({
							title: '上传失败',
							icon: 'none',
							duration: 1000
						});
						uni.hideLoading()
					}
				})
			}
		})
	}
	//修改对应的个人信息
	const changeData = (item) => {
		number.value = []
		unit.value = []
		float.value = []
		type.value = item
		switch (item) {
			case 1:
				for (let i = 1; i <= 80; i++) {
					number.value.push(i)
				}
				if (baseFormData.value.age) {
					pickerData.value = [getIndexByValue(baseFormData.value.age, 1, 80), 0, ]
				} else {
					pickerData.value = [19, 0, 0]
				}
				popup.value.open("bottom")
				break;
			case 2:
				unit.value = ['男', '女']
				if (baseFormData.value.gender) {
					pickerData.value = [0, 0, getIndexByValue(baseFormData.value.gender, 0, 1)]
				} else {
					pickerData.value = [0, 0, 0]
				}
				popup.value.open("bottom")
				break;
			case 3:
				for (let i = 100; i <= 250; i++) {
					number.value.push(i)
				}
				for (let i = 0; i <= 9; i++) {
					float.value.push('.' + i)
				}
				if (baseFormData.value.height) {
					let v1 = Number(baseFormData.value.height.toString().split('.')[0])
					let v2 = Number(baseFormData.value.height.toString().split('.')[1]) ? Number(baseFormData.value
						.height
						.toString().split('.')[1]) : 0
					pickerData.value = [getIndexByValue(v1, 100, 250), v2, 0]
				} else {
					pickerData.value = [70, 0, 0]
				}
				unit.value = ['厘米']
				popup.value.open("bottom")
				break;
			case 4:
				for (let i = 30; i <= 200; i++) {
					number.value.push(i)
				}
				for (let i = 0; i <= 9; i++) {
					float.value.push('.' + i)
				}
				if (baseFormData.value.weight) {
					let v1 = Number(baseFormData.value.weight.toString().split('.')[0])
					let v2 = Number(baseFormData.value.weight.toString().split('.')[1]) ? Number(baseFormData.value
						.weight
						.toString().split('.')[1]) : 0
					pickerData.value = [getIndexByValue(v1, 30, 200), v2, 0]
				} else {
					pickerData.value = [20, 0, 0]
				}
				unit.value = ['公斤']
				popup.value.open("bottom")
				break;
			default:
				break;
		}
	}
	//保存数据到数据库
	const saveData = () => {
		uni.showLoading({
			title: '保存中...'
		})
		switch (type.value) {
			case 1:
				proxy.$http("setUserInfo", {
					age: tempData.value
				}).then(res => {
					if (!res.errCode) {
						uni.showToast({
							title: res.result.msg,
							icon: 'none',
							duration: 1000
						})
						baseFormData.value.age = tempData.value
						userInfo.age = tempData.value
						uni.setStorageSync('userInfo', userInfo)
						uni.hideLoading()
						popup.value.close()
					}
				})
				break;
			case 2:
				proxy.$http("setUserInfo", {
					gender: tempData.value
				}).then(res => {
					if (!res.errCode) {
						uni.showToast({
							title: res.result.msg,
							icon: 'none',
							duration: 1000
						})
						baseFormData.value.gender = tempData.value
						userInfo.gender = tempData.value
						uni.setStorageSync('userInfo', userInfo)
						uni.hideLoading()
						popup.value.close()
					}
				})
				break;
			case 3:
				proxy.$http("setUserInfo", {
					height: tempData.value
				}).then(res => {
					if (!res.errCode) {
						uni.showToast({
							title: res.result.msg,
							icon: 'none',
							duration: 1000
						})
						baseFormData.value.height = tempData.value
						userInfo.height = tempData.value
						uni.setStorageSync('userInfo', userInfo)
						uni.hideLoading()
						popup.value.close()
					}
				})
				break;
			case 4:
				proxy.$http("setUserInfo", {
					weight: tempData.value
				}).then(res => {
					if (!res.errCode) {
						uni.showToast({
							title: res.result.msg,
							icon: 'none',
							duration: 1000
						})
						baseFormData.value.weight = tempData.value
						userInfo.weight = tempData.value
						uni.setStorageSync('userInfo', userInfo)
						uni.hideLoading()
						popup.value.close()
					}
				})
				break;
			default:
				break;
		}
	}
	const bindChange = (e) => {
		if (e.detail.value[0] && !e.detail.value[1] && unit.value.length <= 1) {
			tempData.value = Number(number.value[e.detail.value[0]])
		} else if (e.detail.value[0] && e.detail.value[1]) {
			tempData.value = Number(number.value[e.detail.value[0]] + float.value[e.detail.value[1]])
		} else if (e.detail.value.length == 1 && unit.value.length > 1) {
			tempData.value = e.detail.value[0]
		}

	}
	//根据数值找到对应的索引
	const getIndexByValue = (value, min, max) => {
		if (value > max || value < min) return false
		return value - min
	}
	const inputDialogToggle = () => {
		inputDialog.value.open()
	}
	//修改昵称
	const dialogInputConfirm = (val) => {
		if (val.length > 10) {
			uni.showToast({
				title: '超出10个字符',
				icon: 'error',
				duration: 1000
			})
			return
		}
		uni.showLoading({
			title: '保存中...'
		})
		proxy.$http("setUserInfo", {
			nickName: val
		}).then(res => {
			if (!res.errCode) {
				uni.showToast({
					title: res.result.msg,
					icon: 'none',
					duration: 1000
				})
				baseFormData.value.nickName = val
				userInfo.nickName = val
				uni.setStorageSync('userInfo', userInfo)
				uni.hideLoading()
				inputDialog.value.close()
			}
		})
	}
	//修改个性签名
	const changeSignature = () => {
		uni.navigateTo({
			url: `/pages/signature/signature?signature=${baseFormData.value.signature}`
		})
	}
</script>

<style lang="scss">
	.information {
		height: 100vh;
		width: 100%;
		color: #5b5e62;

		.bg {
			margin: 30rpx 20rpx;
			background: #fff;
			border-radius: 20rpx;

			.box {
				height: 80rpx;
				padding: 20rpx 40rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.signature {
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;
				}

				.image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
				}

				.left {
					width: 50%;
					font-size: 26rpx;
					color: #8d959b;
					font-weight: bold;
				}

				.uni-file-picker__container {
					justify-content: flex-end;
				}

				.file-picker__box-content {
					border: none !important;
				}
			}

			.avatar {
				height: 200rpx;
				padding: 0rpx 40rpx;
			}
		}

		.picker-view {
			width: 100%;
			height: 500rpx;
			margin-top: 20rpx;
		}

		.item {
			// line-height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;
			font-weight: bold;
		}

		.btn {
			height: 70rpx;
			display: flex;
			line-height: 70rpx;
			justify-content: space-between;
			box-shadow: 0 3rpx 10rpx 0rpx #d4d4d4;
			font-size: 34rpx;
			font-weight: bold;

			.save {
				margin-right: 20rpx;
				color: #87C38F;
			}

			.cancel {
				margin-left: 20rpx;
				color: #afafaf;
			}
		}
	}
</style>